﻿#region

using System;
using System.IO;
using System.Messaging;

#endregion

namespace NsbMonitorClientService.QueueManager
{
    public class BasicQueueSender : IQueueSender
    {
        public string SendMessageToQueue(string queueFullPath, string content, string label)
        {
            if (!MessageQueue.Exists(queueFullPath))
            {
                throw new ArgumentException("cannot find queue: " + queueFullPath);
            }


            using (MessageQueue queue = new MessageQueue(queueFullPath))
            {
                string id = null;
                var mqTran = new MessageQueueTransaction();
                if (label == null)
                {
                    label = "";
                }
                mqTran.Begin();
                try
                {
                    Message message = new Message();
                    message.Label = label;
                    StreamWriter writer = new StreamWriter(message.BodyStream);
                    writer.Write(content);
                    writer.Flush();

                    queue.Send(message, label, mqTran);

                    mqTran.Commit();

                    id = message.Id;
                }
                catch (Exception ex)
                {
                    mqTran.Abort();
                }

                return id;
            }
        }
    }
}